package com.example.administrator.szb.activity;

import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.bean.GWJGBean;
import com.example.administrator.szb.bean.IndexBean;
import com.example.administrator.szb.bean.StarBean;
import com.example.administrator.szb.fragments.fragment_forTab.home.adapter.JGadapter;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.SpannableStringUtil;
import com.example.administrator.szb.util.Toasts;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.api.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by D N on 2017/11/30.
 */

public class BGZRSearch_new extends BaseActivity {
    int current_page = 1;
    int per_page = 12;
    int id = 0;
    @Bind(R.id.bgzr_new_recyclerview_title)
    RecyclerView bgzrNewRecyclerviewTitle;
    @Bind(R.id.info_search)
    LinearLayout infoSearch;
    @Bind(R.id.bgrz_new_recyclerview)
    ListView bgrzNewRecyclerview;
    @Bind(R.id.bgrz_new_swipeRefreshlayout)
    SmartRefreshLayout bgrzNewSwipeRefreshlayout;

    View footerview;
    View error_head;
    int one_only = 0;//标题数据只用一次
    GWJGBean gwjgBean;

    ArrayList<GWJGBean.DataBean.ConditListBean> mdata_title = new ArrayList<>();
    ArrayList<IndexBean.DataBean.HotCounBean> mdata_data = new ArrayList<>();


    BaseAdapter<GWJGBean.DataBean.ConditListBean> adapter_title;
    BaseAdapter<GWJGBean.DataBean.DataListBean> adapter_data;
    private int sbzr_id = 0;
    private boolean isFirstEnter = true;


    private TextView aaaaaa;
    String top_tipsStr = "";
    private ImageView right_down;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bgzr_search_new_activity);
        ButterKnife.bind(this);
        id = getIntent().getIntExtra("id",-1);
        SampleApplicationLike.getActivitiesInstance().add(this);
        initToolbarThreeImage(R.id.bgzr_search_new_toolbar_include, "并购转让", R.drawable.search_bs, new Callback() {
            @Override
            public void doSomeThing() {
                startActivity(new Intent(BGZRSearch_new.this, SearchActivity.class));
            }
        });

        footerview = LayoutInflater.from(this).inflate(R.layout.view_wd_footer, null);
        footerview.setVisibility(View.INVISIBLE);
        initRefreshLayout();
    }

    /**
     * 开启刷新监听
     */
    private void initRefreshLayout() {
        right_down = (ImageView) findViewById(R.id.right_down);
        aaaaaa = (TextView) findViewById(R.id.aaaaaa);
        top_tipsStr=aaaaaa.getText().toString();
        aaaaaa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                right_down.setVisibility(View.VISIBLE);
                aaaaaa.setSingleLine(true);
                aaaaaa.setText(top_tipsStr);
            }
        });
        right_down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                right_down.setVisibility(View.GONE);
                aaaaaa.setSingleLine(false);
                SpannableStringUtil stringUtil = new SpannableStringUtil(aaaaaa);
                stringUtil.addText(top_tipsStr);
                stringUtil.addTextWithImg("这是图片",R.mipmap.circle_up,null,new int[]{40,40});
                aaaaaa.setText(stringUtil.getText());

                aaaaaa.setText(stringUtil.getText());

            }
        });
//        bgrzNewSwipeRefreshlayout.setColorSchemeResources(R.color.zhutise);
//        bgrzNewSwipeRefreshlayout.post(new Runnable() {
//            @Override
//            public void run() {
//                current_page = 1;
//                bgrzNewSwipeRefreshlayout.setRefreshing(true);
//                requestData(sbzr_id+"",0);
//            }
//        });
//
//        bgrzNewSwipeRefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                current_page = 1;
//                bgrzNewSwipeRefreshlayout.setRefreshing(true);
//                requestData(sbzr_id+"",0);
//            }
//        });

        if (isFirstEnter) {
            bgrzNewSwipeRefreshlayout.autoRefresh();
        }
        bgrzNewSwipeRefreshlayout.setEnableLoadMore(true);//是否启用上拉加载功能
        bgrzNewSwipeRefreshlayout.setEnableLoadMoreWhenContentNotFull(true);//是否在列表不满一页时候开启上拉加载功能


        bgrzNewSwipeRefreshlayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //refreshlayout.setLoadmoreFinished(false);//恢复上拉状态
                // Toasts.show(getActivity(), "加载更多啊", Toast.LENGTH_SHORT);
                requestData(sbzr_id+"".toString(),1);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                current_page = 1;
                requestData(sbzr_id+"".toString(),0);
                //refreshlayout.finishRefresh();
            }
        });
    }

    private void requestData(String search_id,final int isRefreshOrMore) {
        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("id", id+"");
        map.put("arr", "" + search_id);
        map.put("current_page", current_page + "");
        map.put("per_page", per_page + "");
        String url = URLAddress.URLBASE + URLAddress.URL_GWJG;
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);

        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, GWJGBean.class, url, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                gwjgBean = (GWJGBean) response;
                findViewById(R.id.bgzr_new_net_error).setVisibility(View.GONE);
                if (gwjgBean.getResult() == 1){
                    if (isRefreshOrMore == 0){

                        mdata_data.clear();

                        if(one_only == 0){
                            mdata_title.addAll(gwjgBean.getData().getConditList());
                            one_only = 1;
                        }

                        mdata_data.addAll(gwjgBean.getData().getDataList());
                        bgrzNewSwipeRefreshlayout.finishRefresh();
                        current_page = current_page+1;
                        initView();
                    }

                    else if(isRefreshOrMore == 3){
                        mdata_data.clear();
                        mdata_data.addAll(gwjgBean.getData().getDataList());
                        current_page = current_page+1;
                        bgrzNewSwipeRefreshlayout.finishRefresh();
                        initView();
                    }

                    else if(isRefreshOrMore == 1){
                        current_page = current_page+1;
                        mdata_data.addAll(gwjgBean.getData().getDataList());
                        bgrzNewSwipeRefreshlayout.finishLoadmore();
                    }

                    if (adapter_data != null){
                        adapter_data.notifyDataSetChanged();
                    }
                    bgrzNewSwipeRefreshlayout.finishRefresh();
                }
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                bgrzNewSwipeRefreshlayout.finishLoadmore();
                bgrzNewSwipeRefreshlayout.finishRefresh();
                findViewById(R.id.bgzr_new_net_error).setVisibility(View.VISIBLE);
                findViewById(R.id.bgzr_new_net_error).findViewById(R.id.home_fragment_button_djcs_error).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        requestData(sbzr_id+"",0);
                    }
                });
                error.toString();
            }
        });
    }

    private void initView() {
        initTitleRecyclerview();
        initRecyclerview();
    }
    JGadapter adapter;
    private void initRecyclerview() {
        bgrzNewRecyclerview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(BGZRSearch_new.this, JGXQActivity.class);
                intent.putExtra("id", mdata_data.get(position).getId());
                intent.putExtra("id_type", id);
                startActivity(intent);
            }
        });

        if (mdata_data.size() == 0) {

            String info = "未搜索到相关机构";
            Toasts.show(this,""+info);
        }
        if (adapter==null){
            adapter = new JGadapter(this,mdata_data);
            bgrzNewRecyclerview.setAdapter(adapter);
        }else {
            adapter.notifyDataSetChanged();
        }

    }

    private void initItem(BaseAdapter.BaseViewHolder holder, GWJGBean.DataBean.DataListBean dataBean, int position) {
        if (!TextUtils.isEmpty(dataBean.getZhenshi_img())) {
            Glide.with(this).load(dataBean.getZhenshi_img()).into((ImageView) (holder).getView(R.id.imageView20));
        }
        ((TextView) holder.getView(R.id.textView49)).setText(dataBean.getCompany() + "-" + dataBean.getName());
        if (dataBean.getCompany() == null) {
            ((TextView) holder.getView(R.id.textView50)).setVisibility(View.INVISIBLE);
        } else {
            ((TextView) holder.getView(R.id.textView50)).setVisibility(View.INVISIBLE);
            //((TextView)holder.getView(R.id.textView50)).setText(dataBean.getCompany());
        }
        if (dataBean.getCity() == null) {
            ((TextView) holder.getView(R.id.textView51)).setVisibility(View.INVISIBLE);
        } else {
            ((TextView) holder.getView(R.id.textView51)).setText((String) dataBean.getCity());
        }


        /**
         * 显示业务标签
         */

        showYW(dataBean, holder, position);

        /**
         * 显示星星
         */
        showStar(dataBean, holder);
    }

    private void showStar(final GWJGBean.DataBean.DataListBean dataBean, BaseAdapter.BaseViewHolder holder) {
        final ArrayList<StarBean> mdata = new ArrayList<>();
        RecyclerView recyclerView = ((RecyclerView) holder.getView(R.id.zdyh_recyclerview_star));
        recyclerView.setLayoutManager(new GridLayoutManager(this, 5));
        for (int i = 0; i < 5; i++) {
            StarBean b = new StarBean();
            mdata.add(b);
        }
        BaseAdapter<StarBean> adapter = new BaseAdapter<StarBean>(BGZRSearch_new.this, mdata) {
            @Override
            public void convert(int position, BaseViewHolder holder, StarBean starBean) {
                ((ImageView) holder.getView(R.id.view_zdyh_star)).setImageResource(R.drawable.star_hui);
                if (dataBean.getEvaluate() / 2 > position) {
                    ((ImageView) holder.getView(R.id.view_zdyh_star)).setImageResource(R.drawable.start);
                }
                if (position == dataBean.getEvaluate() / 2 + dataBean.getEvaluate() % 2 - 1 && dataBean.getEvaluate() % 2 != 0) {
                    ((ImageView) holder.getView(R.id.view_zdyh_star)).setImageResource(R.drawable.star_half);
                }
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_zdyh_star;
            }
        };
        recyclerView.setAdapter(adapter);
    }

    private void showYW(GWJGBean.DataBean.DataListBean dataBean, BaseAdapter.BaseViewHolder holder, final int position) {

        RecyclerView recyclerView = ((RecyclerView) holder.getView(R.id.zdyh_recyclerview_ywbq));
        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        /**
         * 截获事件，业务标签的recyclerview 会劫持事件，如果不加上点击失效
         */
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {//此处是点击按下时才执行跳转动作
                    // Toasts.show(mActivity, "....", Toast.LENGTH_SHORT);
                    Intent intent = new Intent(BGZRSearch_new.this, JGXQActivity.class);
                    intent.putExtra("id", mdata_data.get(position).getId());
                    intent.putExtra("id_type", id);
                    startActivity(intent);

                    //startActivity(new Intent(ProfileEdit.this, EditDepartment.class));
                }
                return false;
            }
        });

        BaseAdapter<GWJGBean.DataBean.DataListBean.BusinessIdBean> adapter = new BaseAdapter<GWJGBean.DataBean.DataListBean.BusinessIdBean>(this, dataBean.getBusiness_id(), 4) {
            @Override
            public void convert(int position, BaseViewHolder holder, GWJGBean.DataBean.DataListBean.BusinessIdBean businessBean) {
                GradientDrawable drawable;
                ((TextView) holder.getView(R.id.view_jgxq_text)).setText(businessBean.getTitle());
                /*try {
                    Class<?> c = null;
                    c = Class.forName("bean.ColorBean$DataBean");
                    ColorBean.DataBean obj = (ColorBean.DataBean) c.newInstance();
                    //第一个参数写的是方法名,第二个\第三个\...写的是方法参数列表中参数的类型
                    Method method = c.getMethod("get_$" + businessBean.getId());
                    String str2 = (String) method.invoke(WecomeActivity.colorBean.getData());


                    drawable = (GradientDrawable) ((TextView) holder.getView(R.id.view_jgxq_text)).getBackground();
                    drawable.setColor(Color.parseColor(str2));
                } catch (Exception e) {

                }*/


            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_jgxq_item;
            }
        };
        recyclerView.setAdapter(adapter);
    }



    private void initTitleRecyclerview() {
        adapter_title = new BaseAdapter<GWJGBean.DataBean.ConditListBean>(BGZRSearch_new.this,mdata_title) {
            @Override
            public void convert(final int position, BaseViewHolder holder, final GWJGBean.DataBean.ConditListBean listBean) {
                ((TextView) holder.getView(R.id.sqxm_bgzr_title)).setText(listBean.getTitle());
                if (listBean.getChoose() == 0){
                    ((CheckBox)holder.getView(R.id.sqxm_bgzr_title)).setChecked(false);
                }else if (listBean.getChoose() == 1){
                    ((CheckBox)holder.getView(R.id.sqxm_bgzr_title)).setChecked(true);
                }

                if (position == 0 && listBean.getOnly_one() == 0){
                    mdata_title.get(position).setOnly_one(1);
                    ((CheckBox)holder.getView(R.id.sqxm_bgzr_title)).setChecked(true);
                    //((EditText)info_map.get(-3)).setHint(listBean.getDescbus());//
                    adapter_title.notifyDataSetChanged();
                }

                ((CheckBox)holder.getView(R.id.sqxm_bgzr_title)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        if (b){
                            for (int i = 0; i < mdata_title.size(); i++) {
                                mdata_title.get(i).setChoose(0);
                            }
                            mdata_title.get(position).setChoose(1);
                            adapter_title.notifyDataSetChanged();
                            //((EditText)info_map.get(-3)).setHint(listBean.getDescbus());//
                            current_page = 1;
                            mdata_data.clear();
                            sbzr_id = listBean.getId();
                            requestData(sbzr_id+"",3);
                            //sbzr_title = listBean.getTitle();
                        }
                    }
                });
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_sqxm_item_bgzr;
            }
        };
        bgzrNewRecyclerviewTitle.setLayoutManager(new GridLayoutManager(this,mdata_title.size()));
        bgzrNewRecyclerviewTitle.setAdapter(adapter_title);
    }


}
